from simpy import Resource, Environment

from x_pc.core import Device, DeviceCost, System
from x_pc.model.model import Task


class ZHB(Device, DeviceCost):
    """
    304 综合换包站台
    综合包(ZHB)
    """
    TIME_COST = 10
    # 资源
    resource: Resource = None

    def __init__(self, env: Environment, name: str):
        super().__init__(env, name)
        self.resource = Resource(env)

    def cost(self, *args, **kwargs) -> float:
        return self.TIME_COST


class ZHBSystem(System):
    # TODO: 综合换包站台
    ZHB_NUMS = 2
    # ZHB列表
    zhb_list: list[ZHB] = list()

    def __init__(self, env: Environment, name: str):
        super().__init__(env, name)
        self.__init_zhb_list()

    def __init_zhb_list(self):
        self.zhb_list = [ZHB(self.env, '') for _ in range(self.ZHB_NUMS)]

    def run_task(self, task: Task):
        if not self.zhb_list:
            while self.running:
                yield self.env.timeout(1)
                if self.zhb_list:
                    break
        #
        zhb = self.zhb_list.pop(0)
        with zhb.resource.request() as req:
            yield req
            #
            process = task.process
            process.begin_ts = self.env.now
            #
            yield self.env.timeout(zhb.cost())
            #
            process.end_ts = self.env.now
            # TODO: 根据任务类型，将任务分发至不同的设备
            process.end_pos = None
        #
        self.zhb_list.append(zhb)
